/*
数据接口
*/
function WebAPI() {
	// http://10.66.164.6/api
	// this.serverHead = "http://195.195.195.55/api"; //idc/
	this.serverHead = "http://192.168.100.74/api"; //idc/
	// this.serverHead = "http://192.168.20.229:8080"; //idc/
	// this.serverHead = "http://192.168.20.165:8080"; //idc/
	
	this.roomid = getQueryString("room") ? getQueryString("room") : "d49626e844c448bea49cb9d559e3b5b5";
	this.roomName = "3D机房(老)"

	this.CabInfosCache = null; //机柜数据缓存
	this.CabInfosCacheAll = []; //机柜数据缓存
	this.OtherDevsCache = null; //所有设备缓存
	this.ServerDevsCache = {}; //所有设备缓存
	this.AllDevsCache = null; //所有设备缓存
	this.alarmCache = []; //告警缓存
	this.modelAlarmCache = {}; //模型对应告警缓存
	this.wsSocket = null;
	//告警闪动对应的颜色
	this.alarmColors = {
		"L1": 0xff0000,
		"L2": 0xff6600,
		"L3": 0xffff00,
		"L4": 0x0096ff,
	}
	this.urls = {
		// enables: "/dataDemo/enable.json",
		enables: "/static/dataDemo/enable.json",
		// buildData: "/dataDemo/buildData.json", //统计信息
		buildData: "/static/dataDemo/buildData.json", //统计信息
		racks: "/business/cmdb/roomorrack/getAllData", //机柜信息
		useRates: "/business/cmdb/roomorrack/getUseRates", //机柜利用率
		temperatures: "/business/cmdb/roomorrack/getTemperatures", //温度数据
		bearing: "/business/cmdb/roomorrack/getBearing", //承重
		euRate: `/business/cmdb/roomorrack/getConsumptions`, //功耗
		// uvInfos: "/business/cmdb/roomorrack/getUvInfos", //u位信息
		uvInfos: "/business/cmdb/roomorrack/getUvInfosAll", //u位信息

		// otherDevs: "/dataDemo/otherDev.json", //其它动环设备
		otherDevs: "/dataDemo/otherDev.json", //其它动环设备
		DevData: "/static/dataDemo/otherDevValue.json", //动环设备实时数据
		queryInfos: "/business/cmdb/roomorrack/getHost", //查询接口
		alarms: "/business/cmdb/roomorrack/getAlarms", //告警
		alarmsWebsoket: "xxxx",

	}
}
WebAPI.prototype.getEnables = function () {
	var _this = this;
	var url = this.serverHead + this.urls.enables + "?roomId=" + this.roomid;
	// url += "&r=" + Math.random();
	var enables = null;
	// httpGetSyn(url, function (response) {
	// 	if (response && response.data) {
	// 		enables = response.data;
	// 	}
	// }, function (err) {
	// 	console.log(err);
	// });
	enables = {
		"alarm": true,
		// "space": true,
		"uUse": true,
		// "temp": true,
		// "bearing": true,
		// "energy": true,
		// "search": true
	  }
	return enables;
}
WebAPI.prototype.getBuildData = function () {
	var _this = this;
	var url = this.serverHead + this.urls.buildData + "?roomId=" + this.roomid;
	// url += "&r=" + Math.random();
	// var url2 = this.serverHead + '/business/cmdb/roomorrack/getSingleAll' + "?roomId=" + this.roomid;
	var url2 = this.serverHead + `/business/cmdb/roomorrack/getSingleAll?roomId=${this.roomid}&roomName=${this.roomName}`;
	console.log("url2", url2)
	var buildData = {};
	buildData.racksConfig = []
	buildData.baseConfig = {}
	buildData.roomConfig = []
	buildData.devConfig = []
	// let x = 2100;
	// let z = 1300;
	let x = 3900;
	let z = 2400; // 1300
	let len = 0
	let listAll = []
	// httpGetSyn(url, function(response) {
	// 	if (response && response.data) {
	// 		buildData = response.data;
	// 		console.log('response', response.data)



	// 	}
	// }, function(err) {
	// 	console.log(err);
	// });

	httpGetSyn(url2, function (response) {

		console.log('response, responseresponseresponseresponse', response)
		let arr_ = ['楼层接入配线及设备', '英特网', '视频会议', 'KVM-服务器配线', '服务器机柜7', '服务器机柜8', '服务器机柜9', '服务器机柜10', '服务器机柜11', '服务器机柜12', '运营商机柜',
			'英特网机柜', '广域网机柜', '局域网机柜', '服务器机柜1', '服务器机柜2', '服务器机柜3', '服务器机柜4', '服务器机柜5', '服务器机柜6'
		]


		let list = response.data;

		list = list.sort((a, b) => {
			return arr_.indexOf(a.name) - arr_.indexOf(b.name)
		})

		list.forEach((item, index) => {
			// console.log(index)
			len = index + 1;
			// item.rotation = {
			// 	"x": 0,
			// 	"y": 90,
			// 	"z": 0
			// }
			
			// 3900 8700 z0  4200
			
			x += 700
			
			if ((len - 1) % 4 == 0) {
				x = 5800
				if (len > 0) {
					z += 1200
				}
			}
			
			// if (len > 1) {
			// 	if (len % 2 == 0) { //偶数
			// 		x += 600

			// 	} else { //奇数
			// 		if (len % 5 == 0) { //奇数倍
			// 			x = 9300
			// 		} else {
			// 			x += 600
			// 		}
			// 	}
			// 	if ((len - 1) % 10 == 0) {
			// 		x = 2100
			// 		if (len > 0) {
			// 			z += 1700
			// 		}
			// 	}
			// }


			listAll.push({
				...item,
				"position": {
					"x": x,
					"y": 770,
					"z": z

				},
				"rotation": {
					"x": 0,
					"y": 90,
					"z": 0
				}
			})


		})

		console.log('list', listAll)
		buildData.racksConfig = listAll;
		buildData.baseConfig = {
			"length": 13200,
			"width": 9975,
			"maxheight": 1500,
			"minheight": 0,
			"centerx": 6600,
			"centerz": 4987.5,
			"normRackSize": {
				"depth": 1000,
				"width": 600
			}
		},
		buildData.roomConfig = [{
			"type": "floor",
			"name": "BaseFloor",
			"size": {
				"x": 13200,
				"z": 9975,
				"y": 100
			},
			"CenterPosition": {
				"x": 6600,
				"y": -60,
				"z": 4987.5
			},
			"rotation": {
				"x": 0,
				"y": 0,
				"z": 0
			}
		},
		{
			"type": "wall",
			"name": "wall_4",
			"size": {
				"x": 8780,
				"z": 150,
				"y": 1500
			},
			"startPosition": {
				"x": 4420,
				"y": 0,
				"z": 9975
			},
			"doorHoles": [{
				"type": 0,
				"start": 100,
				"width": 870,
				"height": 1200,
				"thickness": 40
			},
			{
				"type": 2,
				"start": 1900,
				"width": 1350,
				"height": 1200,
				"thickness": 40
			}
			],
			"rotation": {
				"x": 0,
				"y": 0,
				"z": 0
			}
		},


		{
			"type": "glassWall",
			"name": "wall_4_1",
			"size": {
				"x": 4420,
				"z": 10,
				"y": 1500
			},
			"startPosition": {
				"x": 0,
				"y": 0,
				"z": 9975
			},
			"rotation": {
				"x": 0,
				"y": 0,
				"z": 0
			}
		},

		{
			"type": "wall",
			"name": "wall_1",
			"size": {
				"x": 13200,
				"z": 100,
				"y": 1500
			},
			"startPosition": {
				"x": 0,
				"y": 0,
				"z": 0
			},
			"doorHoles": [],
			"rotation": {
				"x": 0,
				"y": 0,
				"z": 0
			}
		},

		{
			"type": "wall",
			"name": "wall_2",
			"size": {
				"x": 9975,
				"z": 100,
				"y": 1500
			},
			"startPosition": {
				"x": 0,
				"y": 0,
				"z": 0
			},
			"doorHoles": [],
			"rotation": {
				"x": 0,
				"y": -90,
				"z": 0
			}
		},
		{
			"type": "wall",
			"name": "wall_3",
			"size": {
				"x": 9975,
				"z": 100,
				"y": 1500
			},
			"startPosition": {
				"x": 13200,
				"y": 0,
				"z": 0
			},
			"doorHoles": [],
			"rotation": {
				"x": 0,
				"y": -90,
				"z": 0
			}
		}
		],
		buildData.devConfig = [

			{
				"type": "jmkt",
				"id": "1",
				"dataId": "kt1",
				"position": {
					"x": 300,
					"z": 1300
				},
				"rotation": {
					"x": 0,
					"y": 0,
					"z": 0
				},
				"scale": {
					"x": 1,
					"y": 1,
					"z": 1
				}
			},
			{
				"type": "jmkt",
				"id": "2",
				"dataId": "kt2",
				"position": {
					"x": 300,
					"z": 4100
				},
				"rotation": {
					"x": 0,
					"y": 0,
					"z": 0
				},
				"scale": {
					"x": 1,
					"y": 1,
					"z": 1
				}
			},
			{
				"type": "pz",
				"id": "3",
				"dataId": "qiuji1",
				"position": {
					"x": 500,
					"z": 9000
				},
				"rotation": {
					"x": 0,
					"y": 0,
					"z": 0
				},
				"scale": {
					"x": 1,
					"y": 0.6,
					"z": 1
				}
			},
			{
				"type": "pz",
				"id": "3",
				"dataId": "qiuji1",
				"position": {
					"x": 12300,
					"z": 9000
				},
				"rotation": {
					"x": 0,
					"y": 0,
					"z": 0
				},
				"scale": {
					"x": 1,
					"y": 0.6,
					"z": 1
				}
			},
			// {
			// 	"type": "UPS",
			// 	"id": "3",
			// 	"dataId": "ups1",
			// 	"position": {
			// 		"x": 6000,
			// 		"z": 1300
			// 	},
			// 	"rotation": {
			// 		"x": 0,
			// 		"y": -90,
			// 		"z": 0
			// 	},
			// 	"scale": {
			// 		"x": 1,
			// 		"y": 1,
			// 		"z": 1
			// 	}
			// },
			// {
			// 	"type": "pdg",
			// 	"id": "4",
			// 	"dataId": "pdg1",
			// 	"position": {
			// 		"x": 6800,
			// 		"z": 1300
			// 	},
			// 	"rotation": {
			// 		"x": 0,
			// 		"y": -90,
			// 		"z": 0
			// 	},
			// 	"scale": {
			// 		"x": 1,
			// 		"y": 1,
			// 		"z": 1
			// 	}
			// },
			// {
			// 	"type": "pdg",
			// 	"id": "5",
			// 	"dataId": "pdg2",
			// 	"position": {
			// 		"x": 7600,
			// 		"z": 1300
			// 	},
			// 	"rotation": {
			// 		"x": 0,
			// 		"y": -90,
			// 		"z": 0
			// 	},
			// 	"scale": {
			// 		"x": 1,
			// 		"y": 1,
			// 		"z": 1
			// 	}
			// }
		]
	}, function (err) {
		console.log(err);
	});


	console.log('buildData', buildData)

	return buildData;
}
WebAPI.prototype.getAlarmColor = function (lstr) {
	return this.alarmColors[lstr] ? this.alarmColors[lstr] : "0xff0000";
}
//数据初始化
WebAPI.prototype.dataInit = function () {
	webapi.getCabInfos(function () {
		webapi.getUDetailInfos(null, function () {
			webapi.getOhterDevs(function () {
				webapi.getAlarms();
				webapi.startWebsocket();
			});
		});

	});
}


/*
获取机柜信息
*/
WebAPI.prototype.getCabInfos = function (suc) {
	var _this = this;
	if (_this.CabInfosCache) {
		return _this.CabInfosCache;
	}
	var url = this.serverHead + this.urls.racks + "?roomId=" + this.roomid;
	// url += "&r=" + Math.random();

	let arr_ = ['楼层接入配线及设备', '英特网', '视频会议', 'KVM-服务器配线', '服务器机柜7', '服务器机柜8', '服务器机柜9', '服务器机柜10', '服务器机柜11', '服务器机柜12', '运营商机柜',
		'英特网机柜', '广域网机柜', '局域网机柜', '服务器机柜1', '服务器机柜2', '服务器机柜3', '服务器机柜4', '服务器机柜5', '服务器机柜6'
	]
	httpGetSyn(url, function (response) {
		if (response && response.data) {
			console.log("response.dataresponse.data??????",response.data)
			let data = response.data;
			data = data.sort((a, b) => {
				return arr_.indexOf(a.name) - arr_.indexOf(b.name)
			})

			console.log(data)
			_this.CabInfosCache = {};
			_this.CabInfosCache.datas = data;
			_this.CabInfosCache.Modelobjs = {};
			_this.CabInfosCache.Dataobjs = {};
			_this.CabInfosCache.DataobjsById = {};
			$.each(data, function (_index, _obj) {
				// console.log(_obj)
				var key = _obj.id;

				_this.CabInfosCache.Dataobjs["d_" + key] = _obj;
				_this.CabInfosCache.DataobjsById["d_" + _obj.id] = _obj;
				var info = getRelationInfoByDataId(key);
				if (info) {
					_this.CabInfosCache.Modelobjs["m_rack_" + info.id] = _obj;
				}

			});
			console.log(_this.CabInfosCache)
			if (suc) {
				suc();
			}
		}
	}, function (err) { });
	return _this.CabInfosCache;
}
/*
获取U位信息
*/
WebAPI.prototype.getUDetailInfos = function (cabnetid, suc) {
	var _this = this;
	// var url = this.serverHead + this.urls.uvInfos + "?roomId=" + this.roomid;
	// var url = this.serverHead + `${this.urls.uvInfos}/d50e9c0bf794415f9d5e99b166ce6654`;
	var url = this.serverHead + `${this.urls.uvInfos}`;
	if (cabnetid) {
		url += "&cabnetId=" + cabnetid;
	}
	console.log('url', url)
	// url += "&r=" + Math.random();
	let CabInfosCacheAll = []
	httpGet(url, function (response) {
		if (response && response.data) {
			// _this.CabInfosCacheAll = response.data || []
			$.each(response.data, function (_index, _obj) {
				if (_obj.servers) {
					_this.CabInfosCache.Dataobjs["d_" + _obj.id].children = _obj.servers;
					if (_obj && _obj.servers) {
						$.each(_obj.servers, function (_sindex, _sobj) {
							_sobj.cabId = _obj.id;
							_this.ServerDevsCache["s_" + _sobj.id] = _sobj;
							CabInfosCacheAll.push(_sobj)
						})
					}
				}

			});
			_this.CabInfosCacheAll = CabInfosCacheAll

			if (suc) {
				suc();
			}
		}
	}, function (err) { });
}


//获取其他环境设备
WebAPI.prototype.getOhterDevs = function (suc) {
	var _this = this;
	if (_this.OtherDevsCache) {
		return _this.OtherDevsCache;
	}
	var url = this.serverHead + this.urls.otherDevs + "?roomId=" + this.roomid;
	// url += "&r=" + Math.random();
	httpGetSyn(url, function (response) {
		if (response && response.data) {
			_this.OtherDevsCache = {};
			_this.OtherDevsCache.datas = response.data;
			_this.OtherDevsCache.Modelobjs = {};
			_this.OtherDevsCache.Dataobjs = {};
			_this.OtherDevsCache.DataobjsById = {};
			$.each(response.data, function (_index, _obj) {
				var key = _obj.id;
				_this.OtherDevsCache.Dataobjs["d_" + key] = _obj;
				_this.OtherDevsCache.DataobjsById["d_" + _obj.id] = _obj;
				var info = getRelationInfoByDataId(key);
				if (info) {
					_this.OtherDevsCache.Modelobjs["m_dev_T_" + info.type + "_ID_" + info.id] =
						_obj;
				}
			});

			console.log(_this.OtherDevsCache.Dataobjs)

			if (suc) {
				suc();
			}
		}
	}, function () { });
	return _this.OtherDevsCache;
}



/*
获取U位信息搜索
*/
WebAPI.prototype.getSearchInfos = function (keyword, suc) {
	console.log('keyword', keyword)
	var _this = this;
	// var url = this.serverHead + this.urls.queryInfos + "?roomId=" + this.roomid;
	var url = this.serverHead + `${this.urls.queryInfos}/${keyword}`
	// if (keyword) {
	// 	url += "&keyword=" + keyword;
	// }
	// url += "&r=" +Math.random();
	httpGet(url, function (response) {
		if (response && response.data) {
			if (suc) {
				suc(response.data);
			}
		}
	}, function (err) { });
}



//获取利用率
WebAPI.prototype.getRacksUsedRateValue = function (sunFunc) {
	var _this = this;
	var url = this.serverHead + this.urls.useRates + "?roomId=" + this.roomid;
	httpGet(url, function (response) {
		if (response && response.data && sunFunc) {
			sunFunc(response.data);
		} else {
			layer.msg("获取利用率数据异常");
		}
	}, function () {
		layer.msg("获取利用率数据异常");

	});
}
//获取承重
WebAPI.prototype.getRacksBearingValue = function (sunFunc) {
	var _this = this;
	var url = this.serverHead + this.urls.bearing + "?roomId=" + this.roomid;
	// url += "&r=" + Math.random();
	httpGet(url, function (response) {
		if (response && response.data && sunFunc) {
			sunFunc(response.data);
		} else {
			layer.msg("获取承重数据异常");
		}
	}, function () {
		layer.msg("获取承重数据异常");

	});

}
//获取温度值
WebAPI.prototype.getTemptureValue = function (sunFunc) {
	var _this = this;
	var url = this.serverHead + this.urls.temperatures
	// + "?roomId=" + this.roomid;
	// url += "&r=" + Math.random();
	httpGet(url, function (response) {
		if (response && response.data && sunFunc) {
			sunFunc(response.data);
		}
	}, function () {
		layer.msg("获取温度数据异常");

	});

}
//获取湿度值
WebAPI.prototype.getHumValue = function (sunFunc) {
	var _this = this;
	var url = this.serverHead + this.urls.euRate + "?roomId=" + this.roomid;
	// url += "&r=" + Math.random();
	httpGet(url, function (response) {
		if (response && response.data && sunFunc) {
			sunFunc(response.data);
		}
	}, function () {
		layer.msg("获取湿度数据异常");

	});

}

//获取告警信息
WebAPI.prototype.getAlarms = function (sunFunc) {
	var _this = this;
	var url = this.serverHead + this.urls.alarms + "?roomId=" + this.roomid;
	// url += "&r=" + Math.random();
	httpGet(url, function (response) {
		webapi.handlerAlarms(response.data);

	}, function () {
		layer.msg("获取告警数据异常");

	});
}
//处理告警数据到缓存中
WebAPI.prototype.handlerAlarms = function (data, issocket) {
	/*
	主要定义了机柜、机柜内设备、其它动环设备这三种类型
	用 1 2 3 分别代表这三种类型

	1 活动告警 2表示已确认告警 3表示已关闭告警

	*/
	if (data) {
		$.each(data, function (_index, _obj) {
			var dev = getRelationInfoByDataId(_obj.devId); //绑定设备信息
			_obj.dev = dev;
			if (dev) {
				if (!webapi.modelAlarmCache["m_" + dev.modelId]) {
					webapi.modelAlarmCache["m_" + dev.modelId] = [];
				}
				_obj.dev.mid = "m_" + dev.modelId;
				webapi.modelAlarmCache["m_" + dev.modelId].push(_obj);
			}
			webapi.alarmCache.push(_obj);
		});
	}

	if (issocket) { //websoket来的数据
		var newAlarms = webapi.alarmCache;
		$.each(data, function (_index, _obj) {
			var dev = getRelationInfoByDataId(_obj.devId); //绑定设备信息
			_obj.dev = dev;
			if (_obj.alarmState == "1") { //新增告警
				if (dev) {
					if (!webapi.modelAlarmCache["m_" + dev.modelId]) {
						webapi.modelAlarmCache["m_" + dev.modelId] = [];
					}
					_obj.dev.mid = "m_" + dev.modelId;
					webapi.modelAlarmCache["m_" + dev.modelId].push(_obj);
				}
				newAlarms.push(_obj);
			} else { //消除
				var newalarm2 = [];
				$.each(newAlarms, function (_cindex, _cobj) {
					if (_cobj.alarmId == _obj.alarmId) {
						if (_cobj.dev && _cobj.dev.modelId) {
							if (webapi.modelAlarmCache["m_" + _cobj.dev.modelId] && webapi
								.modelAlarmCache["m_" + _cobj.dev.modelId].length >= 0) {
								var malaC = [];
								$.each(webapi.modelAlarmCache["m_" + _cobj.dev.modelId], function (
									_mcindex, _mcobj) {
									if (_mcobj.alarmId == _obj.alarmId) { } else {
										malaC.push(_mcobj);
									}
								});
								webapi.modelAlarmCache["m_" + _cobj.dev.modelId] = malaC;
							}
						}

					} else {
						newalarm2.push(_cobj);
					}
				});
				newAlarms = newalarm2;
			}
		});
		webapi.alarmCache = newAlarms;
	}
	console.log(webapi.alarmCache);
	if (webapi.alarmCallBackHandler) {
		webapi.alarmCallBackHandler(webapi.alarmCache);
	}
}
WebAPI.prototype.getAlarmByModelId = function () { }
//websoket方法
WebAPI.prototype.createWebsocket = function () {
	return
	var myWebSocket = new WebSocket(webapi.wsurl);
	myWebSocket.onopen = function (openEvent) {
		var params = {
			action: "test",
		};
		myWebSocket.send(JSON.stringify(params));
	};
	myWebSocket.onmessage = function (messageEvent) {
		console.log(messageEvent);
		if (messageEvent.data && messageEvent.data != "连接成功") {
			var alarmData = JSON.parse(messageEvent.data);
			webapi.handlerAlarms(alarmData.data, true);
		}
	};
	myWebSocket.onerror = function (errorEvent) { };
	myWebSocket.onclose = function (closeEvent) { }
	return myWebSocket;
}

WebAPI.prototype.startWebsocket = function () {
	return

	if (window.WebSocket == null) {
		alert("not support WebSocket");
	} else {
		wsSocket = webapi.createWebsocket();
		/*
		 CONNECTING  (0) Default
		 OPEN (1)
		 CLOSING (2)
		 CLOSED (3)
		*/
		setInterval(function () {
			if (wsSocket.readyState == 1) {
				wsSocket.send("heartbeat");
			} else {
				wsSocket = webapi.createWebsocket();
			}

		}, 10000);
	}

}

var webapi = new WebAPI();